package com.jason.rtsp.controller;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @创建人 zhouhx
 * @创建时间 2023/8/31 16:47
 * @描述
 */
@Controller
public class VideoController {

    private ConcurrentHashMap<String, ChannelHandlerContext> clients = new ConcurrentHashMap<>();

    @RequestMapping("/receive")
    @ResponseBody
    public void receive(HttpServletRequest request){

        try {
            ServletInputStream inputStream = request.getInputStream();
            int length = -1;
            while ((length = inputStream.available())!=-1){
                byte[] data = new byte[length];
                inputStream.read(data);
                sendData(data);
            }

        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public void sendData(byte[] data){
        for(Map.Entry<String,ChannelHandlerContext> entry:clients.entrySet()){
            try {
                if(entry.getValue().channel().isWritable()){
                    entry.getValue().writeAndFlush(new BinaryWebSocketFrame(Unpooled.copiedBuffer(data)));
                }else{
                    clients.remove(entry.getKey());
                }
            }catch (Exception e){
                clients.remove(entry.getKey());
                e.printStackTrace();
            }
        }
    }



    public void setClients(ChannelHandlerContext ctx){
        clients.put(ctx.channel().id().asLongText(),ctx);
    }
}
